import { createRouter, createWebHistory } from 'vue-router'
import authService from '@/services/AuthService'
import permissionService from '@/services/permission.service'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/pages/Login.vue'),
    meta: {
      requiresAuth: false,
      title: '登录 - Matrix Framework'
    }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/pages/Dashboard.vue'),
    meta: {
      requiresAuth: true,
      title: '控制台 - Matrix Framework'
    }
  },
  {
    path: '/tenants',
    name: 'Tenants',
    component: () => import('@/pages/tenants/TenantList.vue'),
    meta: {
      requiresAuth: true,
      title: '租户管理 - Matrix Framework',
      permissions: ['TenantManagement.Tenants']
    }
  },
  {
    path: '/users',
    name: 'Users',
    component: () => import('@/pages/users/UserList.vue'),
    meta: {
      requiresAuth: true,
      title: '用户管理 - Matrix Framework',
      permissions: ['Identity.Users']
    }
  },
  {
    path: '/test-api',
    name: 'TestApi',
    component: () => import('@/views/TestApi.vue'),
    meta: {
      requiresAuth: false,
      title: 'API测试 - Matrix Framework'
    }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/pages/Profile.vue'),
    meta: {
      requiresAuth: true,
      title: '个人资料 - Matrix Framework'
    }
  },
  {
    path: '/unauthorized',
    name: 'Unauthorized',
    component: () => import('@/pages/Unauthorized.vue'),
    meta: {
      requiresAuth: false,
      title: '访问被拒绝 - Matrix Framework'
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫 - 检查认证状态和权限
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title
  }

  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    try {
      const isAuthenticated = await authService.validateTokenEnhanced()

      if (!isAuthenticated) {
        // 未认证，跳转到登录页
        next({
          name: 'Login',
          query: { redirect: to.fullPath }
        })
        return
      }

      // 检查权限要求
      if (to.meta.permissions) {
        const permissions = Array.isArray(to.meta.permissions)
          ? to.meta.permissions
          : [to.meta.permissions]

        const hasRequiredPermission = permissionService.hasAllPermissions(permissions)

        if (!hasRequiredPermission) {
          // 权限不足，跳转到未授权页面
          next({
            name: 'Unauthorized',
            query: { from: to.fullPath }
          })
          return
        }
      }
    } catch (error) {
      console.error('认证检查失败:', error)
      next({
        name: 'Login',
        query: { redirect: to.fullPath }
      })
      return
    }
  }

  // 如果已认证用户访问登录页，跳转到控制台
  if (to.name === 'Login' && authService.user) {
    next({ name: 'Dashboard' })
    return
  }

  next()
})

export default router